<?php

namespace app\admin\controller\rush;

use app\admin\model\User;
use app\common\controller\AdminController;
use app\common\service\RedisService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="抢购日程")
 */
class Schedule extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\RushSchedule();
        
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();

            $admin = session('admin');//
            $param = [];
            if(!empty($admin['uid'])){
                $param['bucket_id'] = $admin['uid'];
            }

            $count = $this->model
                ->where($where)
                ->where($param)
                ->count();
            $list = $this->model
                ->where($where)
                ->where($param)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            foreach($list as &$val){
                $val['bucket_name'] = Db::name("user_bucket")->find($val['bucket_id'])['bucket_name'];
            }
            
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            // 添加并推送
            $save ? self::sync() : false;

            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $admin = session('admin');//
        $param = [];
        if(!empty($admin['uid'])){
            $param['id'] = $admin['uid'];
        }

        $fencang = Db::name("user_bucket")->where($param)->select();
        $this->assign("fencang", $fencang);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            // 添加并推送
            $save ? self::sync() : false;

            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        //
        $admin = session('admin');//
        $param = [];
        if(!empty($admin['uid'])){
            $param['id'] = $admin['uid'];
        }
        $fencang = Db::name("user_bucket")->where($param)->select();
        $this->assign("fencang", $fencang);

        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->update(['id' => $id, "state" => 0]);
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? self::sync() : false;

        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="推送")
     */
    public function sync(){
        $admin = session('admin');  //
        //$list = Db::query("SELECT *,state as schedule_state FROM sy_rush_schedule where bucket_id = '{$admin['uid']}' ORDER BY starttime ASC");
		$list = Db::query("SELECT *,state as schedule_state FROM sy_rush_schedule ORDER BY starttime ASC");
        $data = collection($list)->toArray();
//print_r($data);die;
        //$re = RedisService::select(0)->set(self::KEYS['RUSH_SCHEDULE'] . "{$data['id']}" , json_encode($data, JSON_UNESCAPED_UNICODE ) );
		$re = RedisService::select(0)->set(self::KEYS['RUSH_SCHEDULE'] , json_encode($data, JSON_UNESCAPED_UNICODE ) );
        $this->success('操作成功');
    }

    /**
     * @NodeAnotation(title="获取进场数据")
     */
    public function access($id){

//  redis 获取场次对应的 userid
            $alldata = RedisService::select(3)->hKeys( self::KEYS['LOG_SCHEDULE'] . $id );
            
            $userModel = new \app\admin\model\User();

            //list($page, $limit, $where) = $this->buildTableParames();
            $userids = implode(",",$alldata);
            
            $list = $userModel
                ->where('id', 'in' , $userids )
                ->select();

//            foreach($list as &$val){
//                $val['bucket_name'] = Db::name("user_bucket")->find($val['bucket_id'])['bucket_name'];
//            }

            // $data = [
            //     'code'  => 0,
            //     'msg'   => '',
            //     'count' => 0,
            //     'data'  => $list,
            // ];
            
            $this->assign('list',$list);
           
            // return json($data);
            
        // $alldata = RedisService::select(3)->hKeys( self::KEYS['LOG_SCHEDULE'] . $id );

        // if ($this->request->isAjax()) {
            
        // }
        return $this->fetch();

    }

    public function download(){}


}